<?php

namespace App\Http\Controllers\Admin;

use App\Models\Props;
use App\Models\PropsVal;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PropertyController extends Controller
{
    //商品规格首页
    public function index()
    {
        //规格列表
        $rule_list = Props::query()->where('disabled','0')->orderBy('sort','asc')->get()->toArray();
        foreach($rule_list as &$v){
            $val_name_list = array_column(PropsVal::query()->where([['props_id',$v['props_id']],['disabled','0']])->get()->toArray(),'name');
            $v['val_list'] = implode(',',$val_name_list);
        }
        $data['rule_list'] = $rule_list;

        //参数列表
        return view('admin.property.index',$data);
    }

    //规格创建页面
    public function create_form()
    {
        return view('admin.property.create');
    }

    //规格编辑页面
    public function update_form(Request $request,$props_id)
    {
        $data['val_list'] = [];
        $data['props'] = [];
        $value_list = PropsVal::query()->where([['props_id',$props_id],['disabled','0']])->get()->toArray();
        $props_data = Props::query()->where('props_id',$props_id)->first()->toArray();
        if(!empty($props_data)){
            $data['val_list'] = $value_list;
            $data['props'] = $props_data;
        }
//        dd($data);
        return view('admin.property.update',$data);
    }

    /**规格的创建
     * @param Request $request
     * @param Props $propModel 属性model
     * @return \Illuminate\Http\RedirectResponse
     */
    public function create(Request $request,Props $propModel)
    {
        //验证有效性
        $request->validate([
            'Rule.name' => 'required',
            'Rule.sort' => 'required|integer',
        ]);

        if(!$propModel->store($request->all())){
            return redirect('admin/property/index')->with('danger','添加规格失败');
        }
        return redirect('admin/property/index')->with('success','添加规格成功');
    }

    /**规格的更新
     * @param Request $request
     * @param Props $propModel 属性model
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request,Props $propModel)
    {
        //验证有效性
        $request->validate([
            'Rule.name' => 'required',
            'Rule.sort' => 'required|integer',
        ]);

        if(!$propModel->store($request->all())){
            return redirect('admin/property/index')->with('danger','编辑规格失败');
        }
        return redirect('admin/property/index')->with('success','编辑规格成功');
    }

    /**规格的删除
     * @param Request $request
     * @param Props $propModel 属性model
     * @param Props $props_id 属性id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete(Request $request,Props $propModel,$props_id)
    {
        $propModel->del($props_id);
        return redirect('admin/property/index')->with('success','删除规格成功');
    }
}
